using System;
using System.Collections.Generic;

namespace Framework.StringSplit.Processors
{
    internal class SplitAsKeyValueListProcessor : BaseStringSplitProcessor<List<KeyValuePair<string, string>>>
    {
        public override List<KeyValuePair<string, string>> Process(StringSplitHandler parameters, string text)
        {
            return parameters.SeperatorInnerChar == null
                       ? ProcessKeyValueWithEvenElements(parameters, text)
                       : ProcessKeyValuesWithCustomInnerSeperator(parameters, text);
        }

        private List<KeyValuePair<string, string>> ProcessKeyValueWithEvenElements(StringSplitHandler parameters, string text)
        {
            // Start by using the standard string splitter to get an array of strings 
            // which will need to be further broken up ito key/value pairs
            var keyValues = Split(text, parameters.SeperatorChar, int.MaxValue, false, parameters.Trim);

            if (keyValues.Length % 2 == 1)
            {
                //There may be an odd number of elements so the last key/value pair will have a value off string.Empty
                keyValues = ArrayUtil.AddToStringArray(keyValues, string.Empty);
            }

            var result = new List<KeyValuePair<string, string>>(keyValues.Length / 2);

            for (var i = 0; i < keyValues.Length; i += 2)
            {
                result.Add(new KeyValuePair<string, string>(keyValues[i], keyValues[i + 1]));
            }

            return result;
        }

        private List<KeyValuePair<string, string>> ProcessKeyValuesWithCustomInnerSeperator(StringSplitHandler parameters, string text)
        {
            // Start by using the standard string splitter to get an array of strings 
            // which will need to be further broken up ito key/value pairs
            var keyValues = Split(text, parameters.SeperatorChar, int.MaxValue, false, parameters.Trim);

            var result = new List<KeyValuePair<string, string>>(keyValues.Length);

            foreach (var kv in keyValues)
            {
                var keyValue = Split(kv, parameters.SeperatorInnerChar, 2, false, parameters.Trim);

                var key = keyValue.ElementAtOrDefault(0, string.Empty);
                var value = keyValue.ElementAtOrDefault(1, string.Empty);

                result.Add(new KeyValuePair<string, string>(key, value));
            }

            return result;
        }
    }
}